package com.thread.exe;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class TestInvokeAll {
	private static final ExecutorService exe = Executors.newCachedThreadPool();
	private static int num;
	
	public static void main(String[] args) throws InterruptedException {
		List<IntegerTask> task = new ArrayList<>();
		TestInvokeAll ta = new TestInvokeAll();
		for (int i = 0; i < 5; i++) {
			task.add(ta.new IntegerTask(i));
		}
		task.add(ta.new IntegerTask(0));
		List<Future<Integer>> futures = exe.invokeAll(task, 2000L, TimeUnit.MILLISECONDS);
		
		
		for (Future<Integer> future : futures) {
			Integer result;
			try {
				result = future.get();
				System.out.println(result);
			} catch (ExecutionException e) {
				e.printStackTrace();
			} catch (CancellationException e) {
				e.printStackTrace();
			}
		}
		Thread.sleep(2000L);
		System.out.println(num);
	}
	
	private class IntegerTask implements Callable<Integer>{
		public Integer key;
		
		public IntegerTask(Integer key) {
			super();
			this.key = key;
		}

		public Integer call() throws Exception {
			Thread.sleep(key * 1000L);
			return key;
		}
		
	}
}
